package cn.wolfcode.web.modules.linkman.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.ExcelExportEntityWrapper;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.CityUtils;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysDict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author MAOWEI
 * @since 2023-08-01
 */
@Controller
@RequestMapping("linkman")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;

    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbCustLinkman";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("user/linkman/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("user/linkman/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("user/linkman/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('user:linkman:list')")
    public ResponseEntity page(LayuiPage layuiPage, String parameterName, String custId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        LambdaQueryWrapper<TbCustLinkman> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(parameterName), TbCustLinkman::getLinkman, parameterName)
                .or()
                .like(StringUtils.isNotBlank(parameterName), TbCustLinkman::getPhone, parameterName)
                .or()
                .eq(StringUtils.isNotBlank(custId), TbCustLinkman::getCustId, custId);
        IPage iPage = entityService.page(page, queryWrapper);
        List<TbCustLinkman> tbCustLinkmanList = iPage.getRecords();
        for (TbCustLinkman tbCustLinkman : tbCustLinkmanList) {
            TbCustomer tbCustomer = customerService.getById(tbCustLinkman.getCustId());
            String customerName = tbCustomer.getCustomerName();
            tbCustLinkman.setCustName(customerName);
        }
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(iPage));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module = LogModule)
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('user:linkman:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @PostMapping("export")
    public void export(String parameterName, String custId, HttpServletResponse response) throws UnsupportedEncodingException {
        // 获取要导出的数据
        LambdaQueryWrapper<TbCustLinkman> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId)
                .or()
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getPhone, parameterName)
                .or()
                .like(!StringUtils.isEmpty(parameterName), TbCustLinkman::getLinkman, parameterName);
        List<TbCustLinkman> custLinkmanList = entityService.list(queryWrapper);

        // 执行文件导出，准备工作
        ExportParams exportParams = new ExportParams();

        // 导出
        // 参数一：样式
        // 参数二：导出的实体类字节码
        // 参数三：导出内容
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbCustLinkman.class, custLinkmanList);
        PoiExportHelper.exportExcel(response, "联系人管理名单", workbook);
//
//        Set<String> dictCodes = codes.stream().map(SysDict::getDiceCode).collect(Collectors.toSet());
//        Set<String> parentCodes = codes.stream().map(SysDict::getParentDiceCode).collect(Collectors.toSet());
//        dictCodes.addAll(parentCodes);
//
//        List<Map> dictList = new ArrayList<>(0);
//        if (!CollectionUtils.isEmpty(dictCodes)) {
//            dictList = dictService.queryList(dictCodes);
//        }
//
//
//        ExcelExportEntityWrapper wrapper = new ExcelExportEntityWrapper();
//        wrapper.entity(SysDict.DICE_NAME, "diceName", 20)
//                .entity(SysDict.DICE_CODE, "diceCode", 20)
//                .entity(SysDict.DICE_VALUE, "字典值", 20)
//                .entity("状态", "disable", 20)
//                .entity(SysDict.DESCRIPTION, "description", 20);
//
//        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), wrapper.getResult(), dictList);
//        PoiExportHelper.exportExcel(response, "数据字典列表", workbook);
    }
    @RequestMapping("listByCustomerId")
    public ResponseEntity<ApiModel> listByCustomerId(String custId){
        if(StringUtils.isEmpty(custId)){
            return ResponseEntity.ok(ApiModel.ok());
        }
        System.out.println("cust"+custId);

        List<TbCustLinkman> list = entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId), TbCustLinkman::getCustId, custId).list();
        return ResponseEntity.ok(ApiModel.data(list));
    }
}
